package com.easybenefit.UUService.qrcode;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.InputType;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.easybeanfit.UUService.commutill.UUDialogUtill;
import com.easybeanfit.UUService.commutill.UUJsonUtil;
import com.easybeanfit.UUService.commutill.UULogUtil;
import com.easybeanfit.UUService.commutill.UUNetUtill;
import com.easybeanfit.UUService.commutill.UUSharedUtil;
import com.easybeanfit.UUService.commutill.UUStrUtil;
import com.easybeanfit.UUService.commutill.UUToastUtil;
import com.easybeanfit.UUService.config.UUConfig;
import com.easybeanfit.UUService.config.UUDict;
import com.easybenefit.UUService.BaseActivity;
import com.easybenefit.UUService.R;
import com.easybenefit.UUService.activity.CouponsDistributedListActivity;
import com.easybenefit.UUService.model.HttpCouponBean;
import com.easybenefit.UUService.model.UserInfo;
import com.easybenefit.UUService.myinterface.IActivityInterface;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.InvertedLuminanceSource;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.PlanarYUVLuminanceSource;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.qrcode.QRCodeMultiReader;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;


import org.apache.http.Header;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class QrcodeActivity extends BaseActivity implements IActivityInterface, View.OnClickListener {
    private final String TAG = "QrcodeActivity";
    private Context context;
    private SurfaceView sfvCamera;
    private SFHCamera sfhCamera;
    private View centerView;
    private Timer mTimer;
    private MyTimerTask mTimerTask;
    // 按照标准HVGA
    private int width;
    private int height;
    int dstLeft, dstTop, dstWidth, dstHeight;
    private boolean isOpen;

    private Dialog dialog; // 确认提示框
    private boolean islocation = true;
    private ProgressDialog progressDialog;
    private String scanresult = "";
    private final int REQUEST_CODE_ASK_CAMERA = 1;
    private Button btn_back, btn_add;//返回和发布
    private Button btn_open;
    private TextView tv_title;
    private boolean isThreadOpen = true;
    private String type;
    private String coupon_id;//优惠券id

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_CAMERA:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    this.recreate();
                } else {
                    // Permission Denied
                    Toast.makeText(context, "没有相机权限", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        setContentView(R.layout.v_qrcode);
        initView();

    }

    public void initData() {

        btn_add.setText(getResources().getText(R.string.coupons_hexiao));
        type = getIntent().getStringExtra("type");
        switch (type) {
            case "CouponsDistributedListActivity":
                btn_add.setVisibility(View.GONE);
                btn_back.setText(getResources().getText(R.string.distributed_tick));
                tv_title.setText(getIntent().getStringExtra("coup_name"));
                coupon_id = getIntent().getStringExtra("coupon_id");
                break;
            case "MainActivity":
                tv_title.setText("");
                break;
            default:

                break;
        }
    }

    public void initTimer() {
        // 初始化定时器
        mTimer = new Timer();
        mTimerTask = new MyTimerTask();
        mTimer.schedule(mTimerTask, 0, 1000);


    }

    @Override
    public void initView() {
        if (Build.VERSION.SDK_INT >= 23) {
            int hasWriteContactsPermission = context.checkSelfPermission(Manifest.permission.CAMERA);
            if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CODE_ASK_CAMERA);
                return;
            }
        }
        btn_back = (Button) findViewById(R.id.finish_btn);
        tv_title = (TextView) findViewById(R.id.top_title);
        btn_add = (Button) findViewById(R.id.btn_add);
        btn_open = (Button) findViewById(R.id.btn_open);
        isOpen = false;
        WindowManager windowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        centerView = (View) this.findViewById(R.id.centerView);
        sfvCamera = (SurfaceView) this.findViewById(R.id.sfvCamera);
        height = windowManager.getDefaultDisplay().getWidth();
        width = windowManager.getDefaultDisplay().getHeight();
//        height=480;
//        width=640;

        UULogUtil.e("hei_wid", "height:" + height + "  width:" + width);
        if (height == 1080) {
            width = 1920;
        } else if (windowManager.getDefaultDisplay().getWidth() == 720) {
            width = 1280;
        } else if (windowManager.getDefaultDisplay().getWidth() == 480) {
            width = 800;
        }
        sfhCamera = new SFHCamera(sfvCamera.getHolder(), width, height, previewCallback, this);

        initData();
        initListener();
        focus();
        //开启解码线程
        //sfhCamera.startEncode();
        initTimer();
    }

    @Override
    public void initListener() {
        btn_back.setOnClickListener(this);
        btn_add.setOnClickListener(this);
        btn_open.setOnClickListener(this);
        centerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                focus();
                return false;
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.e("onstart", "onstart");


    }


    private void showCenterDialog() {
        View view = getLayoutInflater().inflate(R.layout.dialog_set_coupons, null);
        initButton(view);
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup
                .LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = Gravity.CENTER;
        wl.y = Gravity.CENTER;
        wl.width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 240,
                getResources().getDisplayMetrics());
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
        dialog.onWindowAttributesChanged(wl);
        dialog.setCanceledOnTouchOutside(true);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                initTimer();
            }
        });
        dialog.show();
    }

    private void initButton(View view) {
        Button sureBtn, cancelBtn;
        final EditText editText;
        sureBtn = (Button) view.findViewById(R.id.sure_btn);
        cancelBtn = (Button) view.findViewById(R.id.cancel_btn);
        editText = (EditText) view.findViewById(R.id.et_code);
        editText.setInputType(InputType.TYPE_CLASS_NUMBER);
        sureBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String result = editText.getText().toString().trim();
                if (!UUStrUtil.isEmpty(result)) {
                    final AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
                    builder2.setMessage("是否使用？");
                    builder2.setTitle("提示");
                    builder2.setPositiveButton("是", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            submit(result);
                        }
                    });
                    builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    builder2.show();
                } else {
                    UUToastUtil.showToast(context, "优惠券号码不符合条件");
                }

            }
        });
        cancelBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.e("onstop", "onstop");

    }


    public void focus() {
//        if (dstLeft == 0) {//只赋值一次
//            dstLeft = centerView.getLeft();
//            dstTop = findViewById(R.id.flt_top).getHeight() + findViewById(R.id.llt_top).getHeight();
//            dstWidth = centerView.getWidth();// (centerView.getRight() - centerView.getLeft());
//            dstHeight = centerView.getHeight(); //(centerView.getBottom() - centerView.getTop());
//        }
        Log.i("ltwh", dstLeft + "+" + dstTop + "+" + dstWidth + "+" + dstHeight);
        sfhCamera.AutoFocusAndPreviewCallback();
    }

    class MyTimerTask extends TimerTask {
        @Override
        public void run() {

            if (dstLeft == 0) {//只赋值一次
                dstLeft = centerView.getLeft();
                dstTop = findViewById(R.id.flt_top).getHeight() + findViewById(R.id.llt_top).getHeight();
                dstWidth = centerView.getWidth();
                dstHeight = centerView.getHeight();
            } else {
                mTimer.cancel();
            }
            Log.i("ltwh", dstLeft + "+" + dstTop + "+" + dstWidth + "+" + dstHeight);
//            sfhCamera.AutoFocusAndPreviewCallback();

        }
    }

    private Camera.PreviewCallback previewCallback = new Camera.PreviewCallback() {
        @Override
        public void onPreviewFrame(byte[] data, Camera arg1) {
            //取得指定范围的帧的数据
            if (isThreadOpen) {
                new Thread(new MyRunnable(data)).start();
                isThreadOpen = false;
            }
        }
    };

    class MyRunnable implements Runnable {
        private byte[] data;

        public MyRunnable(byte[] data) {
            this.data = data;
        }

        @Override
        public void run() {
            try {
                //优化竖屏下扫二维码
                UULogUtil.e("start", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                byte[] rotatedData = new byte[data.length];
                for (int y = 0; y < height; y++) {
                    for (int x = 0; x < width; x++)
                        rotatedData[x * height + height - y - 1] = data[x + y * width];
                }
                data = rotatedData;
                //height和width可以调换dstLeft, dstTop, dstWidth, dstHeight
                // PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, height, width, dstLeft, dstTop, dstWidth, dstHeight, true);

                PlanarYUVLuminanceSource source = new PlanarYUVLuminanceSource(data, height, width, dstLeft, dstTop, dstWidth, dstHeight, false);
                //取得灰度图


                BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
                // QRCodeMultiReader reader=new QRCodeMultiReader();
                MultiFormatReader reader = new MultiFormatReader();
                Map<DecodeHintType, Object> hints = new Hashtable<>();
                hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
                //Result result = reader.decode(bitmap, hints);
                Result result = reader.decode(bitmap, hints);
                Message message = new Message();
                message.obj = result;
                handler.sendMessage(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.e("end", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            isThreadOpen = true;
        }
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //mTimer.cancel();
            sfhCamera.cancelEncode();
            updateView((Result) msg.obj);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("onDestroy", "onDestroy");
        try {

            sfhCamera.surfaceDestroyed(sfvCamera.getHolder());
            islocation = false;
//            mTimer.cancel();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void updateView(Result result) {


        Intent intent;
        scanresult = result.getText();

        Log.e("解析结果", scanresult);
        switch (type) {
            case "CouponsDistributedListActivity":
                AlertDialog.Builder builder = new AlertDialog.Builder(context);
                builder.setMessage("是否派发？");
                builder.setTitle("提示");
                builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        distributed_submit(scanresult);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder.show();

                break;
            case "MainActivity":
                AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
                builder2.setMessage("是否使用？");
                builder2.setTitle("提示");
                builder2.setPositiveButton("是", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        submit(scanresult);
                    }
                });
                builder2.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builder2.show();
                break;
            default:
                submit(scanresult);
                break;
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.finish_btn:
                finish();
                break;
            case R.id.btn_open:
                //开关灯
                btn_open.setEnabled(false);
//                mTimer.cancel();
//                sfhCamera.cancelAutoFocus();
                if (sfhCamera != null) {
                    Camera.Parameters parameters = sfhCamera.getMCamera().getParameters();
                    if (isOpen) {
                        isOpen = false;
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                        sfhCamera.getMCamera().setParameters(parameters);
                        btn_open.setText("开灯");

                    } else {
                        isOpen = true;
                        parameters.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                        sfhCamera.getMCamera().setParameters(parameters);
                        btn_open.setText("关灯");

                    }
                    btn_open.setEnabled(true);
//                    initTimer();
                }
                break;
            case R.id.btn_add:
                //这个是showdialog
                mTimer.cancel();
                showCenterDialog();
                break;
            default:
                break;
        }
    }

    /**
     * 核销
     *
     * @param result
     */
    public void submit(String result) {
        String url = UUConfig.SERVER_BASE_URL + "usecoupon";
        String mer_id = ((UserInfo) UUSharedUtil.getObject(context, UUConfig.UU_USERINFO_NAME, UserInfo.class)).getMer_id();
        RequestParams params = new RequestParams();
        params.put("coupon", result);
        params.put("mer_id", mer_id);
        if (!UUNetUtill.isConnected(context)) {
            UUToastUtil.showToast(context, UUDict.NOT_INTERNET);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(context, "正在操作请稍后....");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    UULogUtil.e("content", content);
                    HttpCouponBean http = (HttpCouponBean) UUJsonUtil.fromJson(content, HttpCouponBean.class);
                    if("200".equals(http.getCode())){
                        AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
                        builder2.setMessage(new String(http.getMessage()));
                        builder2.setTitle("提示");
                        builder2.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        });
                        builder2.show();
                    }else{
                        UUToastUtil.showToast(context, new String(http.getMessage()));
                        sfhCamera.resumeEncode();
                    }
//                    if (dialog != null && !dialog.isShowing()) {
//                        dialog.dismiss();
//                        sfhCamera.resumeEncode();
//                    } else if (dialog == null) {
//                        sfhCamera.resumeEncode();
//                    }
                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    try {
                        UUToastUtil.showToast(context, "请使用正确的优惠券码");

                        UULogUtil.e("onFailure", new String(bytes));
                        if (dialog != null && !dialog.isShowing()) {
                            sfhCamera.resumeEncode();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            });
        }
    }


    /**
     * 派发
     *
     * @param result
     */
    public void distributed_submit(String result) {
        String url = UUConfig.SERVER_BASE_URL + "distrcoupon";
        String mer_id = ((UserInfo) UUSharedUtil.getObject(context, UUConfig.UU_USERINFO_NAME, UserInfo.class)).getMer_id();
        RequestParams params = new RequestParams();
        params.put("mem_seq", result);
        params.put("coupon_id", coupon_id);
        params.put("mer_id", mer_id);
        if (!UUNetUtill.isConnected(context)) {
            UUToastUtil.showToast(context, UUDict.NOT_INTERNET);
        } else {
            AsyncHttpClient client = new AsyncHttpClient();
            client.post(url, params, new AsyncHttpResponseHandler() {
                @Override
                public void onStart() {
                    progressDialog = UUDialogUtill.getLoadingBar(context, "正在操作请稍后....");
                    progressDialog.show();
                }

                @Override
                public void onFinish() {
                    progressDialog.dismiss();
                }

                @Override
                public void onSuccess(int i, Header[] headers, byte[] bytes) {
                    String content = new String(bytes);
                    UULogUtil.e("content", content);
                    HttpCouponBean http = (HttpCouponBean) UUJsonUtil.fromJson(content, HttpCouponBean.class);
                    switch (http.getCode()) {
                        case "200":
                            AlertDialog.Builder builder2 = new AlertDialog.Builder(context);
                            builder2.setMessage(new String(http.getMessage()));
                            builder2.setTitle("提示");
                            builder2.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    finish();
                                }
                            });
                            builder2.show();
                            break;
                        default:
                            UUToastUtil.showToast(context, new String(http.getMessage()));
                            sfhCamera.resumeEncode();
//                            if (dialog != null && !dialog.isShowing()) {
//                                initTimer();
//                            } else if (dialog == null) {
//                                initTimer();
//                            }
                            break;
                    }

                }

                @Override
                public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                    if (dialog != null && !dialog.isShowing()) {
                        initTimer();
                    }
                }
            });
        }
    }
}
